//
//  VarietyListViewController.m
//  PigMarket
//
//  Created by mac on 2019/4/4.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "VarietyListViewController.h"
#import "VarietyListCell.h"
#import "VarietyHorizontalListCell.h"
#import "VarietyHeaderView.h"
#import "AdoptDetailViewController.h"

@interface VarietyListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
/**
 顶部菜单栏
 */
@property (nonatomic , strong) VarietyHeaderView *topMenueView;

/**
 flowLayout
 */
@property (nonatomic , strong) UICollectionViewFlowLayout *flowLayout;
/**
 collectionview
 */
@property (nonatomic , strong) UICollectionView *collectionView;
/**
 dataArr
 */
@property (nonatomic , strong) NSMutableArray *dataArr;
/**
 是否显示横向列表  默认显示纵向列表
 */
@property (nonatomic , assign) BOOL defaultArrange;
/**
 currentPage
 */
@property (nonatomic , assign) int currentPage;
/**
 是否按重量排序:0否,1是
 */
@property (nonatomic , assign) BOOL weightArrange;
/**
 是否按价格排序:0否,1是
 */
@property (nonatomic , assign) BOOL priceArrange;
/**
 是否按出栏日期排序:0否,1是
 */
@property (nonatomic , assign) BOOL dateArrange;
/**
 升序:asc,降序:desc  如果是默认排序:则是个空字符串
 */
@property (nonatomic , strong)  NSString *defaultArrangeStr;
/**
 导航猪种类
 */
@property (nonatomic , strong) UIButton *varietyNameBtn;
/**
 猪的种类
 */
@property (nonatomic , strong) NSMutableArray *varietyNameArr;
@end

@implementation VarietyListViewController


#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"三元猪领养";
    [self setUpNav];
    [self setUpView];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[PullDownMenu sharedInstance] hide];
}
#pragma mark - init method
- (void)setUpNav {
    self.navigationItem.titleView = self.varietyNameBtn;
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 60, 44);
    [rightBtn setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
    [rightBtn setTitle:@"更改部落" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [rightBtn addTarget:self action:@selector(changeTribe) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

}
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}

- (void)initView {
    [self.view addSubview:self.topMenueView];
    [self.view addSubview:self.collectionView];
}

- (void) initLayout {
    [self.topMenueView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(40, 0, 0, 0));
    }];
}

- (void) initAction {
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self pigListRequest];
    }];
    [self.collectionView.mj_header beginRefreshing];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.currentPage ++;
        [self pigListMoreRequest];
    }];
    self.collectionView.mj_footer.hidden = YES;
    
    [self.varietyNameBtn addTarget:self action:@selector(detailTypeClick:) forControlEvents:UIControlEventTouchUpInside];

    
    @weakify(self);
    [self.topMenueView setButtonClickBlock:^(ButtonType buttonType,UIButton *button) {
        @strongify(self);
        switch (buttonType) {
            case ButtonTypeDefault:
            {
                [self defaultTapped:button];
            }
                break;
            case ButtonTypeWeight:
            {
                [self weightTapped:button];
            }
                break;
            case ButtonTypePrice:
            {
                [self priceTapped:button];
            }
                break;
            case ButtonTypeDate:
            {
                [self dateTapped:button];
            }
                break;
            case ButtonTypeChangeArrange:
            {
                [self changeArrangeStyleTapped:button];
            }
                break;
            default:
                break;
        }
    }];
    
    
}

- (void)initData {
    self.defaultArrange = YES;
    self.defaultArrangeStr = @"";
    
    NSArray *titleArr = @[@"白猪",@"黑猪"];
    for (int i = 0; i < 2; i ++) {
        PullDownMenuModel *model = [[PullDownMenuModel alloc] init];
        model.icon = @"";
        model.title = titleArr[i];
        
        model.isSelect = NO;
        [self.varietyNameArr addObject:model];
    };
}

#pragma mark - delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat itemW = 0;
    CGFloat itemH = 0;
    
    if (self.defaultArrange) {
        itemW = SCREEN_WIDTH ;
        itemH = 160;
    }else {
        itemW = (SCREEN_WIDTH - 30) / 2;
        itemH = 234;
    }
    return CGSizeMake(itemW, itemH);
}
//调节item边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (self.defaultArrange) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }else {
        return UIEdgeInsetsMake(10, 10, 10, 10);
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.defaultArrange) {//默认横向排序
         VarietyListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VarietyListCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];

        if (self.dataArr.count > 0 && self.dataArr.count > indexPath.row) {
            cell.adoptModel = self.dataArr[indexPath.row];
        }
        return cell;
    }else {
         VarietyHorizontalListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VarietyHorizontalListCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        if (self.dataArr.count > 0 && self.dataArr.count > indexPath.row) {
            cell.adoptModel = self.dataArr[indexPath.row];
        }
        return cell;
    }
    return nil;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    Adopt *adoptModel = self.dataArr[indexPath.row];
    //保存部落ID
    UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
    userInfo.pigId = adoptModel.pigId;
    [UserInfoDataProvider sharedInstance].userInfo = userInfo;

    AdoptDetailViewController *adoptDetailVC = [[AdoptDetailViewController alloc] init];

    [self.navigationController pushViewController:adoptDetailVC animated:YES];
}

#pragma mark - target action
//更改部落
- (void)changeTribe {
    [self.navigationController popViewControllerAnimated:YES];
}
//默认
- (void)defaultTapped:(UIButton *)button {
    self.weightArrange = YES;
    self.weightArrange = NO;
    self.priceArrange = NO;
    self.dateArrange = NO;
    self.defaultArrangeStr = @"";
    [self pigListRequest];
}
//体重
- (void)weightTapped:(UIButton *)button {
    self.weightArrange = YES;
    self.priceArrange = NO;
    self.dateArrange = NO;
    self.defaultArrangeStr = button.selected ? @"desc" : @"asc";
    [self pigListRequest];
}
//价格
- (void)priceTapped:(UIButton *)button {
    self.weightArrange = YES;
    self.priceArrange = YES;
    self.weightArrange = NO;
    self.dateArrange = NO;
    self.defaultArrangeStr = button.selected ? @"desc" : @"asc";
    [self pigListRequest];
}
//出栏日期
- (void)dateTapped:(UIButton *)button {
    self.weightArrange = YES;
    self.dateArrange = YES;
    self.weightArrange = NO;
    self.priceArrange = NO;
    self.defaultArrangeStr = button.selected ? @"desc" : @"asc";
    [self pigListRequest];
}
//切换排列方式
- (void)changeArrangeStyleTapped:(UIButton *)button {
    self.defaultArrange = !self.defaultArrange;
    [self.collectionView reloadData];
}
- (void)detailTypeClick:(UIButton *)button {
    button.selected = !button.selected;
    PMLog(@"===%u",button.selected);
    if (button.selected) {
        @weakify(self);;
        [[PullDownMenu sharedInstance] showWithFrame:CGRectMake(0, TopBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT) type:PullDownTypeTransicationTypes dataArr:self.varietyNameArr completionBlock:^(NSString *text, NSInteger idx ,PullDownType pullWownType) {
            @strongify(self);
            if ([text isEqualToString:@"白猪"]) {
            } else if ([text isEqualToString:@"黑猪"]){
            }
            //修改title和img的edge
            [self.varietyNameBtn setTitle:text forState:UIControlStateNormal];
            [self changeBtnEdge];
            self.varietyNameBtn.selected = !self.varietyNameBtn.selected;
            [self.dataArr removeAllObjects];
            [self pigListRequest];
        }];
    } else {
        [[PullDownMenu sharedInstance] hide];
    }
}
#pragma mark - private method
- (void)pigListRequest {
    self.currentPage = 1;
    [self.dataArr removeAllObjects];
    NSNumber *tribeId = [UserInfoDataProvider sharedInstance].userInfo.tribeId;
    
    AdoptParam *param = [[AdoptParam alloc] init];
    param.page = @(self.currentPage);
    param.limit = @10;
    param.tribeId = tribeId;
    param.varietiesId = self.varietiesId;
    param.sortWeightIf = self.weightArrange ? @(1) : @(0);
    param.sortPriceIf = self.priceArrange ? @(1) : @(0);
    param.sortExpectOutDateIf = self.dateArrange ? @(1) : @(0);
    param.sortType = self.defaultArrangeStr;
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] AdoptPigListWithParam:param] subscribeNext:^(AdoptList * _Nullable adoptList) {
        @strongify(self);
        [self.dataArr addObjectsFromArray:adoptList.list];
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        if (self.currentPage == [adoptList.totalPage intValue] || [adoptList.totalPage intValue] == 0) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];;
        } else {
            self.collectionView.mj_footer.hidden = NO;
        }

    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}
- (void)pigListMoreRequest {
    NSNumber *tribeId = [UserInfoDataProvider sharedInstance].userInfo.tribeId;
    
    AdoptParam *param = [[AdoptParam alloc] init];
    param.page = @(self.currentPage);
    param.limit = @10;
    param.tribeId = tribeId;
    param.varietiesId = self.varietiesId;
    param.sortWeightIf = self.weightArrange ? @(1) : @(0);
    param.sortPriceIf = self.priceArrange ? @(1) : @(0);
    param.sortExpectOutDateIf = self.dateArrange ? @(1) : @(0);
    param.sortType = self.defaultArrangeStr;
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] AdoptPigListWithParam:param] subscribeNext:^(AdoptList * _Nullable adoptList) {
        @strongify(self);
        [self.dataArr addObjectsFromArray:adoptList.list];
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        if (self.currentPage == [adoptList.totalPage intValue] || [adoptList.totalPage intValue] == 0) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];;
        } else {
            self.collectionView.mj_footer.hidden = NO;
        }
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}
- (void)changeBtnEdge {
    NSInteger titleW = self.varietyNameBtn.titleLabel.intrinsicContentSize.width + 2;
    NSInteger imgW = self.varietyNameBtn.imageView.intrinsicContentSize.width + 2;
    [self.varietyNameBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgW, 0, imgW)];
    [self.varietyNameBtn setImageEdgeInsets:UIEdgeInsetsMake(0, titleW, 0, -titleW)];
}
#pragma mark - getter and setter

- (UICollectionViewFlowLayout *)flowLayout {
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    }
    return _flowLayout;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor globalBackgroundColor];
        [_collectionView registerClass:[VarietyListCell class] forCellWithReuseIdentifier:@"VarietyListCell"];
        [_collectionView registerClass:[VarietyHorizontalListCell class] forCellWithReuseIdentifier:@"VarietyHorizontalListCell"];
    }
    return _collectionView;
}
- (VarietyHeaderView *)topMenueView {
    if (!_topMenueView) {
        _topMenueView = [[VarietyHeaderView alloc] init];
        _topMenueView.backgroundColor = [UIColor whiteColor];
     }
    return _topMenueView;
}
- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
- (UIButton *)varietyNameBtn {
    if (!_varietyNameBtn) {
        _varietyNameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _varietyNameBtn.frame = CGRectMake(0, 0, 100, 30);
        [_varietyNameBtn setTitle:@"白猪" forState:UIControlStateNormal];
        [_varietyNameBtn setTitleColor:[UIColor textBlackColor] forState:UIControlStateNormal];
        _varietyNameBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        [_varietyNameBtn setImage:[UIImage imageNamed:@"user_myasset_transicationdetail_up"] forState:UIControlStateNormal];
        [_varietyNameBtn setImage:[UIImage imageNamed:@"user_myasset_transicationdetail_down"] forState:UIControlStateSelected];
        [self changeBtnEdge];
    }
    return _varietyNameBtn;
}
- (NSMutableArray *)varietyNameArr {
    if (!_varietyNameArr) {
        _varietyNameArr = [[NSMutableArray alloc] init];
    }
    return _varietyNameArr;
}
@end
